import java.util.Date;
import java.util.Random;

public class SellThread extends Thread{

    CDshop shop;
    SellThread(CDshop s){
        super();
        this.shop=s;
        this.setDaemon(true);
        this.setName(this.getName()+"sell");
    }

    @Override
    public void run() {
        while (true) {
            Random r = new Random();
            int index = r.nextInt(10)+1;
            int num = r.nextInt(5)+1;
            try {
                synchronized (shop) {
                    while (true) {
                        boolean sold = shop.sell(index,num);
                        if (sold) {
                            break;
                        } else {
                            if (r.nextBoolean()) {
                                System.out.println(new Date() + Thread.currentThread().getName() + index + "数量不足，不销售");
                                break;
                            } else {
                                System.out.println(new Date() + Thread.currentThread().getName() + index + "数量不足，继续等候,唤醒进货线程");
                                shop.notifyAll();
                                shop.wait(r.nextInt(200));
                            }
                        }
                    }
                }
                int sleep=r.nextInt(200);
                System.out.println(new Date() + Thread.currentThread().getName() +"睡眠时间"+sleep);
                this.sleep(sleep);
            } catch (Exception e) {
            }
        }
    }

}
